package com.zqc.security;

import com.zqc.entity.SysUser;
import com.zqc.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 根据用户名去数据库查找用户信息
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    public SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        return new AccountUserDetail(user.getId(), user.getUsername(), user.getPassword(), getUserAuthorities(user.getId()));
    }

    /**
     * 获取用户的角色、菜单权限
     * @param id
     * @return
     */
    public Collection<? extends GrantedAuthority> getUserAuthorities(Long id) {
        String userAuthority =  userService.getUserAuthority(id);
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(userAuthority);
        return grantedAuthorities;
    }
}
